from cameralib import *
from time import time, sleep
from Tkinter import *
from ImageTk import PhotoImage
import sys
import Image
from time import time
import tkFont

webcam = Webcam(resolution='lo')

root = Tk()
# w, h = 640, 480
# root.overrideredirect(1)
# root.geometry("%dx%d+100+100" % (w,h))
# root.focus_set()
root.bind('<Escape>', lambda e: root.quit())

frame = Frame(root)
frame.grid()
canvas = Canvas(frame, width=640*2, height=480*2)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
stream = webcam.stream('numpy')


class Display:
  def __init__(self, canvas):
    self.canvas = canvas
    self.total = 0
    self.start = time()
    self.refresh_delay = 100
    font = tkFont.Font(family="Georgia", size=26)
    self.text = canvas.create_text(100, 600, anchor=NW, font=font, text="", tag='text')

    # performing color filtering
    x = stream.next()
    x = apply_filter(x, array([
      [1, 0, 0],
      [0, 1, 0],
      [0, 0, 1]]))
    x = convert_numpy_pil(x)
    self.image = PhotoImage(x.transpose(Image.FLIP_LEFT_RIGHT))
    self.canvas.create_image(0, 0, anchor=NW, image=self.image, tag='pic')
        
  def refresh(self):
    def myfun(x):
      xr = x[:,0]
      xg = x[:,1]
      xb = x[:,2]
      xg[xg < 150] = 0
      xb[xb < 150] = 0
      xg[xb > 150] = 0
      xb[xg > 150] = 0
      return array([xr, xg, xb]).T
    canvas = self.canvas
    x = apply_filter(stream.next(), array([
      [0,0,0],
      [0,1,0],
      [0,0,1]]), myfun)
    x = convert_numpy_pil(x)
    self.image = PhotoImage(x.resize((1024,768)).transpose(Image.FLIP_LEFT_RIGHT))
    canvas.itemconfigure('pic', image=self.image)
    self.total += 1; 
    if self.total and (self.total % 20) == 0:
      duration = time() - self.start
      canvas.itemconfigure('text', text='Frame rate: %.2f' % (self.total / duration))
    canvas.update()
    canvas.after(self.refresh_delay, self.refresh)
  
Display(canvas).refresh()

root.mainloop()

del webcam
